import pandas as pd
import numpy as np
data1=pd.read_excel('广西.xlsx')
data2=pd.read_excel('湖北.xlsx')
data3=data1.append(data2)
data4=data3[data3['产品通用名称']=='复混肥料']
data=data4.iloc[:,4:7]
print(data)

# 构建聚类模型
from sklearn.cluster import KMeans
# k为聚类类别，iteration为聚类最大循环次数，data_zs为标准化后的数据
# 分成几类可以在此处调整
k = 4
iteration = 500

#数据标准化
data_zs = 1.0 * (data - data.mean()) / data.std()
model = KMeans(n_clusters=k, max_iter=iteration, random_state=1234)
model.fit(data_zs)

# r1统计各个类别的数目，r2找出聚类中心
r1 = pd.Series(model.labels_).value_counts()
r2 = pd.DataFrame(model.cluster_centers_)
r = pd.concat([r2,r1], axis=1)
r.columns = list(data.columns) + ['类别数目']
print(r)
r = pd.concat([data, pd.Series(model.labels_, index=data.index)], axis=1)
r.columns = list(data.columns) + ['聚类类别']
# a=({'0':'1','1':'2','2':'3','3':'4'})
# r['标签'] = r['标签'].astype(str).replace(a)
r['标签']=r.apply(lambda x:x['聚类类别']+1,axis=1)
r['标签']=r['标签'].astype(int)
print(r['标签'].value_counts())
print(r)
r.to_excel('result2_3.xlsx',index=False)


#聚类中心的坐标
Muk=model.cluster_centers_
print(Muk)

#绘制聚类中心的散点图
from pyecharts.charts import *
from pyecharts import options as opts
data_3d=[(-0.35640024,-0.51243794,1.33501947), (1.33430165,-0.20328059,-0.58620693),(-0.5814393,1.31524039,0.13955975),(-0.54622376,-0.68507372,-0.48933417)]
range_color = ['#313695', '#4575b4', '#74add1','#abd9e9']
scatter3D = (Scatter3D()
             .add("", data_3d)
             .set_global_opts(title_opts=opts.TitleOpts(title="聚类3D散点图"),visualmap_opts=opts.VisualMapOpts(max_=0.5))
             )

scatter3D.render('3d聚类.html')

#绘制聚类点的3D散点图
from sklearn.cluster import Birch  #BIRCH模块导入
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
data_1=r[r['标签']==1]
data_2=r[r['标签']==2]
data_3=r[r['标签']==3]
data_4=r[r['标签']==4]
x1=data_1['总氮百分比'].tolist()
y1=data_1['P2O5百分比'].tolist()
z1=data_1['K2O百分比'].tolist()
x2=data_2['总氮百分比'].tolist()
y2=data_2['P2O5百分比'].tolist()
z2=data_2['K2O百分比'].tolist()
x3=data_3['总氮百分比'].tolist()
y3=data_3['P2O5百分比'].tolist()
z3=data_3['K2O百分比'].tolist()
x4=data_4['总氮百分比'].tolist()
y4=data_4['P2O5百分比'].tolist()
z4=data_4['K2O百分比'].tolist()
fig=plt.figure()
ax=fig.add_subplot(111,projection='3d')
ax.scatter(x1,y1,z1,c='m')
ax.scatter(x2,y2,z2,c='r')
ax.scatter(x3,y3,z3,c='g')
ax.scatter(x4,y4,z4,c='c')
#颜色包括 g b y r c m k
plt.show()


#绘制散点矩阵图
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.font_manager import FontProperties
myfont=FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf',size=15)
sns.set(font=myfont.get_name())
sns.pairplot(data=r,hue='标签',vars=['总氮百分比', 'P2O5百分比','K2O百分比'])
plt.show()

#绘制雷达图
df1=r[r['标签']==1]
df2=r[r['标签']==2]
df3=r[r['标签']==3]
df4=r[r['标签']==4]
x1n=round(df1['总氮百分比'].mean(),3)
x1p=round(df1['P2O5百分比'].mean(),3)
x1k=round(df1['K2O百分比'].mean(),3)
x2n=round(df2['总氮百分比'].mean(),3)
x2p=round(df2['P2O5百分比'].mean(),3)
x2k=round(df2['K2O百分比'].mean(),3)
x3n=round(df3['总氮百分比'].mean(),3)
x3p=round(df3['P2O5百分比'].mean(),3)
x3k=round(df3['K2O百分比'].mean(),3)
x4n=round(df4['总氮百分比'].mean(),3)
x4p=round(df4['P2O5百分比'].mean(),3)
x4k=round(df4['K2O百分比'].mean(),3)
from pyecharts.charts import Radar
from pyecharts import options as opts
v1=[[x1n,x1p,x1k]]
v2=[[x2n,x2p,x2k]]
v3=[[x3n,x3p,x3k]]
v4=[[x4n,x4p,x4k]]
radar1=(
    Radar()
    .add_schema(# 添加schema架构
        schema=[
            opts.RadarIndicatorItem(name='总氮百分比',max_=0.3),# 设置指示器名称和最大值
            opts.RadarIndicatorItem(name='P2O5百分比',max_=0.3),
            opts.RadarIndicatorItem(name='K2O百分比',max_=0.3),

        ]
    )
    .add('第一类',v1,color="#f9713c") # 添加一条数据，参数1为数据名，参数2为数据，参数3为颜色
    .add('第二类',v2,color="#4169E1")
    .add('第三类',v3,color="#00BFFF")
    .add('第四类',v4,color="#ffff00")
    .set_global_opts(title_opts=opts.TitleOpts(title='聚类雷达图'),)
)
radar1.render('聚类雷达图.html')









